use crate::utils::db_source::init_mysql;

#[derive(Debug, PartialEq, Eq, Default)]
pub struct UserInfo {
    pub id: u32,
    pub user_name: String,
    pub password: Option<String>,
}

#[allow(dead_code)]
pub fn save(user_info: UserInfo) -> u64 {
    let sql = "INSERT INTO ssm.t_user_info(user_name,password) VALUES (?,?)";
    let p = init_mysql();
    let result = p.prep_exec(sql, (user_info.user_name, user_info.password, )).unwrap().last_insert_id();
    result
}

#[allow(dead_code)]
pub fn delete_by_id(id: i32) {
    let sql = "DELETE FROM ssm.t_user_info WHERE id = ?";
    let p = init_mysql();
    p.prep_exec(sql, (id, )).unwrap();
}

#[allow(dead_code)]
pub fn query_by_id(id: i32) -> Option<UserInfo> {
    println!("id:{}", id);
    let sql = "SELECT id, user_name, password FROM ssm.t_user_info WHERE id = ?";
    let p = init_mysql();
    let mut selected: Vec<UserInfo> = p
        .prep_exec(sql, (id, ))
        .map(|result| {
            result
                .map(|x| x.unwrap())
                .map(|row| {
                    let (id, user_name, password) = mysql::from_row(row);
                    UserInfo { id, user_name, password }
                })
                .collect()
        })
        .unwrap();

    if selected.len() > 0 {
        return selected.pop();
    }
    Option::None
}

#[allow(dead_code)]
pub fn update_by_id(id: i32, user_name: String) {
    let sql = "UPDATE ssm.t_user_info SET user_name = ? WHERE id = ?";
    let p = init_mysql();
    p.prep_exec(sql, (user_name, id, )).unwrap();
}

#[allow(dead_code)]
pub fn check_login(user_name: String, password: String) -> i32 {
    let sql = "SELECT COUNT(*) FROM ssm.t_user_info WHERE user_name = ? AND password = ?";
    let p = init_mysql();
    let result = p.prep_exec(sql, (user_name, password, )).unwrap().next().unwrap().unwrap().unwrap();
    return result.get(0).unwrap().as_sql(true).parse::<i32>().unwrap();
}

#[allow(dead_code)]
pub fn query_all() -> Vec<UserInfo> {
    let p = init_mysql();

    let user_infos: Vec<UserInfo> =
        p.prep_exec("SELECT id, user_name,password FROM ssm.t_user_info", ())
            .map(|result| {
                result.map(|x| x.unwrap()).map(|row| {
                    let (id, user_name, password) = mysql::from_row(row);
                    UserInfo {
                        id,
                        user_name,
                        password,
                    }
                }).collect()
            }).unwrap();
    return user_infos;
}